package com.gym.cors;

import org.springframework.context.annotation.Configuration;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 跨域配置类
 *
 * @author Gym
 */
@Configuration
public class GlobalCorsConfig implements Filter {

    /**
     * 项目初始化
     *
     * @param filterConfig
     */
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String originHeader = httpServletRequest.getHeader("Origin") != null ? httpServletRequest.getHeader("Origin").replace(" ", "")
                : httpServletRequest.getHeader("Origin");
        // 判断数组中是否包含请求中的origin，如果包含就做跨域设置，否则就是不被允许跨域的地址，不做跨域设置
        httpServletResponse.setHeader("Access-Control-Allow-Origin", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "*");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");

        // 这里还可以添加一些想对reponse header添加的信息
        chain.doFilter(request, httpServletResponse);
    }

    @Override
    public void destroy() {
    }
}